#include "stdafx.h"
#include "libraries.h"

#include "Application.h"
#include "GpuBufferManipulator.h"
#include "Filesystem.h"

using namespace Cvekas;

class Triangle : public Application
{
public:
	Triangle(HINSTANCE instance, const std::string& name, const std::string& log_filename)
		:
	Application(instance, name, log_filename)
	{
		Filesystem::init();
	}

	virtual ~Triangle() {}

	virtual void initVideoDevice()
	{
		settings->insert("video", VideoSettings());

		(*settings)["video"]["ScreenWidth"] = 800;
		(*settings)["video"]["ScreenHeight"] = 600;
		(*settings)["video"]["VSync"] = false;
		(*settings)["video"]["Fullscreen"] = false;

		window = WindowPtr(new Window(instance, name));
		video_device->init(window);
	}

	virtual void init()
	{
		// Loading effect
		effect = video_device->getEffectManager()->load("triangle", Filesystem::redirect("Triangle.fx"));

		// Creating vertex buffer
		triangle_vb = video_device->getGpuBufferManager()->createVertexBuffer("triangle_vb", VertexPosColor::getFormat(), 3, false);
		
		// Filling vertex buffer
		GpuBufferManipulator<VertexPosColor> triangle_vb_manipulator(triangle_vb);

		triangle_vb_manipulator.set(0, VertexPosColor(Vector3(-0.5f, -0.5f, 0.5f), Color(255, 0, 0)));
		triangle_vb_manipulator.set(1, VertexPosColor(Vector3(0.0f, 0.5f, 0.5f), Color(0, 255, 0)));
		triangle_vb_manipulator.set(2, VertexPosColor(Vector3(0.5f, -0.5f, 0.5f), Color(0, 0, 255)));

		triangle_vb_manipulator.apply();

		batch.priority = 0;
		batch.batch_id = 0;
		batch.effect_id = effect->getId();
		batch.pass = 0;
		batch.vb_id = triangle_vb->getId();
		batch.ib_id = Resource::INVALID_ID;
		batch.start_index = 0;
		batch.tri_count = 1;
		batch.owner = NULL;
	}

	virtual bool update()
	{
		return true;
	}

	virtual bool render()
	{
		video_device->beginScene();

		main_renderer->prepare(batch);
		main_renderer->render();

		video_device->endScene();

		main_renderer->endFrame();

		return true;
	}

private:
	EffectPtr effect;
	VertexBufferPtr triangle_vb;
	Batch batch;
};

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR pCmdLine, int nShowCmd)
{
	Triangle demo(hInstance, "Triangle", "Triangle.log");
	try
	{
		demo.run();
	}
	catch (std::exception& e)
	{
		MessageBox(NULL, e.what(), "Fatal error", NULL);
	}
	return 0;
}
